import { commonRoutes, asyncRoutes, anyRoutes } from '@/router/routes'
import { getUserInfo, postUserInfo, reqLogout } from '@/utils/api/user'
import { LoginForm } from '@/utils/api/user/type'
import { getToken, removeToken, setToken } from '@/utils/token'
import { defineStore } from 'pinia'
import router from '@/router/index'

export const useUserStore = defineStore('user', {
  state: () => {
    return {
      token: getToken(),
      menuRoute: commonRoutes,
      avatar: 'https://react-project-try-1320075701.cos.ap-guangzhou.myqcloud.com/%E5%A4%B4%E5%83%8F.jpg',
      name: '',
      roles: [] as string[],
      buttons: [] as string[],
      routes: [] as string[]
    }
  },
  actions: {
    // 登录
    async post_user_info_async(data: LoginForm) {
      const res = await postUserInfo(data)
      if (res.data.code === 200) {
        this.token = res.data.data
        setToken(res.data.data)
      }
    },

    // 退出登录
    async post_logout() {
      const res = await reqLogout()
      if (res.data.code == 200) {
        // 清空用户数据
        this.token = null
        this.menuRoute = commonRoutes
        this.name = ''
        this.roles = []
        this.buttons = []
        removeToken()
      }
    },

    // 获取用户信息
    async get_user_info() {
      const res = await getUserInfo()
      if (res.data.code === 200) {
        // 过滤存在的异步路由
        this.menuRoute = [...commonRoutes, ...filterAsyncRoute(asyncRoutes, res.data.data.routes)]
        // anyRoute 必须要加否则会出先刷新后404
        ;[...filterAsyncRoute(asyncRoutes, res.data.data.routes), anyRoutes].forEach((item: any) => {
          router.addRoute(item)
        })
        this.routes = res.data.data.routes
        this.avatar = res.data.data.avatar
        this.name = res.data.data.name
        ;(this.roles = res.data.data.roles), ((this.buttons as string[]) = res.data.data.buttons)
      } else {
      }
    }
  },
  getters: {}
})

// 过滤异步路由
function filterAsyncRoute(asyncRoute: any, route: any) {
  return asyncRoute.filter((item: any) => {
    if (route.includes(item.name)) {
      // 必须要加item.children否则将会咋undefined上读取length
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, route)
      }
      return true
    }
  })
}
